package com.ainiyar.springweb.util;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**************************************
 * File Name : FileUtil
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/4  13:56
 * Desc :文件处理类
 ***************************************/
public class FileUtil {
    //文件存储路径
    private static final String filePath = System.getProperty("user.dir") + "/upload";

    /**
     * 上传文件
     *
     * @param upload 文件流
     * @param path   路径
     * @return
     */
    public static String uploadFile(MultipartFile upload, String path) throws IOException {
        synchronized (FileUtil.class) {
            String flag = System.currentTimeMillis() + "";
            String fileName = upload.getOriginalFilename();
            String file_path = filePath;
            if (path != null) {
                file_path = filePath + "/" + path;
            }
            //判断该路径是否存在
            File file = new File(file_path);
            if (!file.exists()) {
                //如果这个文件夹不存在的话,就创建这个文件
                file.mkdirs();
            }
            //文件存储形式：时间戳+文件名
            upload.transferTo(new File(file_path, flag + "_" + fileName));
            return flag;
        }
    }

    /**
     * 上传图片
     * @param upload 文件流
     * @return Object
     */
    public static Map<String,String> uploadImg(MultipartFile upload) throws IOException {
        synchronized (FileUtil.class) {
            String flag = System.currentTimeMillis() + "";
            String fileName = upload.getOriginalFilename();
            String file_path = filePath;
            file_path = filePath + "/imgs";
            //判断该路径是否存在
            File file = new File(file_path);
            if (!file.exists()) {
                //如果这个文件夹不存在的话,就创建这个文件
                file.mkdirs();
            }
            //文件存储形式：时间戳+文件名
            upload.transferTo(new File(file_path, flag + "_" + fileName));
            Map<String,String> map=new HashMap<>();
            map.put("name",fileName);
            map.put("src",flag);
            return map;
        }
    }

    /**
     * 下载/预览文件
     *
     * @param flag     文件名
     * @param response 返回体
     */
    public static void download(String flag, HttpServletResponse response) {
        File file = new File(filePath);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        List<String> fileNames = listFileName();
        String files_path = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (!ToolsUtil.isNullOrEmpty(files_path)) {
                File pre_file = new File(files_path);
                Path filePath = Paths.get(files_path);
                String filesName = String.valueOf(filePath.getFileName());
                String extension = filesName.substring(filesName.lastIndexOf(".") + 1);
                if (extension.equals("svg")) {
                    // 设置响应头
                    response.setContentType("image/svg+xml");
                    response.addHeader("Content-Length", "" + pre_file.length());
                    try (FileInputStream fileInputStream = new FileInputStream(pre_file); OutputStream outputStream = response.getOutputStream()) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                } else {
                    byte[] data = Files.readAllBytes(filePath);
                    // 设置响应头
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filesName, StandardCharsets.UTF_8));
                    response.addHeader("Content-Length", "" + pre_file.length());
                    // 以流的形式下载文件
                    OutputStream os = response.getOutputStream();
                    os.write(data);
                    os.flush();
                    os.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("下载失败");
        }

    }

    private static List<String> listFileName() {
        Path startPath = Paths.get(filePath);
        List<String> list = new ArrayList<>();
        try {
            Files.walk(startPath)
                    .filter(Files::isRegularFile)
                    .forEach(paths -> list.add(String.valueOf(paths)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 删除指定文件
     * @param flag 指定文件
     * @return true:成功  false:失败
     */
    public static boolean del(String flag){
        try{
            List<String> fileNames = listFileName();
            String files_path = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
            if (ToolsUtil.isNullOrEmpty(files_path)){
                throw new RuntimeException("文件不存在");
            }
            File file = new File(files_path);
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

